//
//  DownloadManager.m
//  AssetDownloader
//
//  Created by Mathieu on 4/10/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "DownloadManager.h"
#import "WordsAppDelegate.h"
#import "DictionariesController.h"
#import "DictionaryMO.h"
#import "DictProtocolDictionary.h"
#import "StardictDict.h"
#import <Foundation/Foundation.h>

@implementation DownloadManager

- (void)awakeFromNib{
	downloadLocations = [[NSMutableDictionary alloc] init];
	[[downloaderWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mathieutozer.com/words/dictionaries/dictionariesDownloader.html"]]];
	[downloaderWebView reload:self];
}

//this get's called somewhere along the chain of command starting with the dropper view.
-(void)downloadContentsOfURL:(NSURL *)url toLocation:(NSString *)location
{
	NSString *homeDir = NSHomeDirectory();
	NSString *applicationSupportFolder = [[[NSFileManager defaultManager] findSystemFolderType:kApplicationSupportFolderType 
																					 forDomain:kOnSystemDisk] stringByStandardizingPath];
	//create a temp assests folder if there isn't one available already
	NSString *tempAssetsFolder = [NSString stringWithFormat:@"%@%@/Words/TempAssets/", homeDir, applicationSupportFolder];
	[[NSFileManager defaultManager] createDirectoryAtPath:[tempAssetsFolder stringByStandardizingPath] attributes:nil];
	
	if(location == nil){ //set a default		
        location = [NSString stringWithString:tempAssetsFolder];
	}
	
	NSString *filename = [[url path] lastPathComponent];
	NSString *fullLocation = [location stringByAppendingPathComponent:filename];
	// create the request
	NSURLRequest *theRequest = [NSURLRequest requestWithURL:url
											  cachePolicy:NSURLRequestUseProtocolCachePolicy
										  timeoutInterval:60.0];
	
	// create the connection with the request
	// and start loading the data
	NSURLDownload  *theDownload=[[NSURLDownload alloc] initWithRequest:theRequest
															  delegate:self];
	[downloadProgressIndicator startAnimation:nil];
	if (theDownload) {
		// set the destination file now
		[theDownload setDestination:fullLocation allowOverwrite:YES];
		NSLog(@"Download descriptoon %@", [theDownload description]);
		[downloadLocations setValue:fullLocation forKey:[theDownload description]];
	} else {
		NSLog(@"Computer Said No");
		// inform the user that the download could not be made
	}
	

}

- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
    // release the connection
    [download release];
	
    // inform the user
    NSLog(@"Download failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}

- (void)downloadDidFinish:(NSURLDownload *)download
{	
	//do something with the data
	NSString *location = [downloadLocations objectForKey:[download description]];
	[self importDownloadedDictionaryAtLocation:location];
		
	// release the connection
	[download release];
}

-(void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path
{
    // path now contains the destination path
    // of the download, taking into account any
    // unique naming caused by -setDestination:allowOverwrite:
    NSLog(@"Final file destination: %@",path);
}

- (void)setDownloadResponse:(NSURLResponse *)aDownloadResponse 
{
    [aDownloadResponse retain];
    [downloadResponse release];
    downloadResponse = aDownloadResponse;
}

- (NSURLResponse *)downloadResponse {
		return downloadResponse;
}

- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response
{
    // reset the progress, this might be called multiple times
    bytesReceived=0;
	
    // retain the response to use later
    [self setDownloadResponse:response];
}

- (BOOL)download:(NSURLDownload *)download
     shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType;
{
    BOOL shouldDecode=NO;
    if ([encodingType isEqual:@"application/gzip"]) {
		NSLog(@"Should decode");
        shouldDecode=YES;
    }
    return shouldDecode;
}

- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(unsigned)length
{
    long long expectedLength=[[self downloadResponse] expectedContentLength];
	
    bytesReceived=bytesReceived+length;
	
    if (expectedLength != NSURLResponseUnknownLength) {
        // if the expected content length is 
        // available, display percent complete
        float percentComplete=(bytesReceived/(float)expectedLength)*100.0;
		[downloadProgressIndicator setDoubleValue:percentComplete];
    } else {
        // if the expected content length is 
        // unknown just log the progress
		[downloadProgressIndicator setIndeterminate:YES];
    }
}

- (void)importDownloadedDictionaryAtLocation:(NSString *)location{
	if(location == nil){
		NSLog(@"Error! Location to import downloaded dictionary from was nil!");
		return;
	}
	
	if([[location pathExtension] isEqualToString:@"gz"]){
			//we need to decompress the file
		NSLog(@"Decompressing dictionary at location: %@", location);
		
		NSTask *task;
		task = [[NSTask alloc] init];
		[task setLaunchPath: @"/usr/bin/gunzip"];
		
		NSArray *arguments;
		arguments = [NSArray arrayWithObjects: location, nil];
		[task setArguments: arguments];
		
			[downloadProgressIndicator setIndeterminate:YES];
			[downloadProgressIndicator startAnimation:nil];
			[downloaderProgressMessage setStringValue:@"Decompressing..."];
			[task launch]; //do the work
			[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(finishedDecompressing:) 
													 name:NSTaskDidTerminateNotification object:task];
			[downloaderProgressMessage setStringValue:@"Installing..."];
			return;
	}
	else{
		[self installDictAtLocation:location];
	} 

}

-(void)finishedDecompressing:(NSNotification *)notification{
	NSString *location = [[[notification object] arguments] objectAtIndex:0];
	NSLog(@"importing dictionary at location: %@", location);
	DictionaryMO *aDictionary;
	//this unarchives the dictionary object and implicitly inserts it into the user's datastore.
	//get rid of the gz from the location string
	NSString *wordsDict = [location stringByDeletingPathExtension];
	NSLog(@"newPath: %@", wordsDict);
	aDictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:wordsDict];
	

	//remove the temp file
	[[NSFileManager defaultManager] removeFileAtPath:wordsDict handler:nil];
	[downloaderProgressMessage setStringValue:@"Finished"];
	[downloadProgressIndicator setIndeterminate:NO];
	[downloadProgressIndicator stopAnimation:nil];
}

-(void)installDictAtLocation:(NSString *)location{
	DictionaryMO *aDictionary;
	aDictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:location];
	//remove the temp file
	[[NSFileManager defaultManager] removeFileAtPath:location handler:nil];
	[downloaderProgressMessage setStringValue:@"Finished"];
	[downloadProgressIndicator setIndeterminate:NO];
	[downloadProgressIndicator stopAnimation:nil];
	
}

@end
